<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="客户编号">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入客户编码"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入客户名称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Upload" @click="handleImport"
          >导入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Download" @click="handleExport"
          >导出</el-button
        >
      </el-col>

      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      border
      :data="supplierList"
    >
      <el-table-column label="序号" width="60" type="index" align="center">
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="mes_people_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="客户编码" width="170" align="center" prop="code">
        <template v-slot="{ row }">
          <el-button type="primary" link @click="handleView(row)">{{
            row.code
          }}</el-button>
        </template>
      </el-table-column>
      <el-table-column
        label="客户名称"
        align="center"
        width="100"
        prop="name"
      />
      <el-table-column label="客户类型" align="center" prop="ctype">
        <template #default="scope">
          <dict-tag :options="mes_custom_ctype" :value="scope.row.ctype" />
        </template>
      </el-table-column>
      <el-table-column label="客户简称" align="center" prop="shorter" />
      <el-table-column
        label="客户渠道"
        width="100"
        align="center"
        prop="channel"
      >
        <template #default="scope">
          <dict-tag :options="mes_custom_channel" :value="scope.row.channel" />
        </template>
      </el-table-column>
      <el-table-column
        label="所属地区"
        width="180"
        align="center"
        prop="area"
      />
      <el-table-column
        label="所属部门"
        width="120"
        align="center"
        prop="dept"
      />
      <el-table-column label="业务专员" align="center" prop="person" />
      <el-table-column label="公司电话" align="center" prop="tel" />
      <el-table-column label="主联系人" align="center" prop="contacts" />
      <el-table-column label="联系电话" align="center" prop="phone" />

      <el-table-column
        label="备注"
        align="center"
        prop="remark"
        :show-overflow-tooltip="true"
      />

      <el-table-column
        label="操作"
        fixed="right"
        align="center"
        min-width="150"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-tooltip content="编辑" placement="top">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleEdit(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDle(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-button
            link
            type="primary"
            icon="TurnOff"
            @click="handleService(scope.row)"
            >{{ scope.row.status == 0 ? "停用" : "启用" }}</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      style="margin-top: 0; padding-top: 0"
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      v-model="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox
                v-model="upload.updateSupport"
              />是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
              >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
 
<script setup name="customer">
import {
  listCustom,
  delCustom,
  changeMesCustomStatus,
  customerExport,
  customerTemplate,
} from "@/api/basicInfo/customer.js";
const { proxy } = getCurrentInstance();
const { mes_custom_ctype, mes_people_status, mes_custom_channel } =
  proxy.useDict("mes_custom_ctype", "mes_people_status", "mes_custom_channel");
import { downLoadBlob } from "@/utils/ruoyi";
import { ElMessage, ElMessageBox } from "element-plus";
const router = useRouter();
const supplierList = ref([]);
const loading = ref(false);
const total = ref(0);

const showSearch = ref(true);
import { getToken } from "@/utils/auth";
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/mes/custom/importData",
});
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    code: null,
    name: null,
  },
  rules: {
    code: [{ required: true, message: "客户编码不能为空", trigger: "blur" }],
    name: [{ required: true, message: "客户名称不能为空", trigger: "blur" }],
  },
});
const { queryParams, form, rules } = toRefs(data);
// 查看
const handleView = (row) => {
  router.push({
    path: "/basicInfo/customer/details",
    query: {
      id: row.id,
      readonly: true,
      code: row.code,
      status: row.status,
    },
  });
};
// 新增
const handleAdd = () => {
  router.push("/basicInfo/customer/details");
};
const handleEdit = (row) => {
  router.push({
    path: "/basicInfo/customer/details",
    query: {
      id: row.id,
      code: row.code,
      status: row.status,
    },
  });
};
//停用启用
const handleService = (row) => {
  const state = row.status === 0 ? "1" : "0";
  const stateText = row.status === 0 ? "停用" : "启用";
  ElMessageBox.confirm(
    `确定要 ${stateText} 名称为 ${row.name} 的客户信息吗?`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(() => {
    // 用户点击了确定按钮
    changeMesCustomStatus(row.id, state).then((response) => {
      if (response.code === 200) {
        ElMessage({
          message: `${stateText}成功`,
          type: "success",
        });
        getList();
      }
    });
  });
};

//删除
const handleDle = (row) => {
  ElMessageBox.confirm(
    "确定要删除名称为 " + row.name + " 的客户信息吗?",
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      // 用户点击了确定按钮
      delCustom(row.id).then((response) => {
        if (response.code === 200) {
          ElMessage({
            message: "删除成功",
            type: "success",
          });
          getList();
        }
      });
    })
    .catch(() => {
      //取消
    });
};
function getList() {
  loading.value = true;
  listCustom(queryParams.value)
    .then((response) => {
      supplierList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    })
    .catch((err) => {
      loading.value = false;
    });
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  queryParams.value.code = null;
  queryParams.value.name = null;
  handleQuery();
}
// 导出
const handleExport = () => {
  customerExport(queryParams.value).then((res) => {
    downLoadBlob(res, "客户列表");
  });
};
/** 导入按钮操作 */
function handleImport() {
  upload.title = "客户导入";
  upload.open = true;
}
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
      response.msg +
      "</div>",
    "导入结果",
    { dangerouslyUseHTMLString: true }
  );
  getList();
};
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}
/** 下载模板操作 */
function importTemplate() {
  customerTemplate().then((res) => {
    downLoadBlob(res, "客户模版");
  });
}

getList();
</script>
 